package com.zjhb.common.controller;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.zjhb.common.dao.BaseDao;
import com.zjhb.common.util.ImageUploadUtil;
import com.zjhb.common.util.ResponseUtil;
import com.zjhb.entity.FileEntity;

@Controller
@RequestMapping("/")
public class DownloadUtil {

	@Autowired
	BaseDao baseDao;

	@RequestMapping(params = { "imageUpload" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	public void imageUpload(HttpServletRequest request, HttpServletResponse response) {
		try {
			ImageUploadUtil.ckeditor(request, response);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping("/down/{id}")
	@ResponseBody
	public void download(HttpServletRequest req, @PathVariable String id, HttpServletResponse resp) {
		FileEntity file = baseDao.getById(FileEntity.class, id);
		UploadController.downloadFile(file.getFileId(),file.getName(),resp);

	}
	
	@RequestMapping("/upload")
	@ResponseBody
	public JSONObject upload(HttpServletRequest req) {
		JSONObject j = new JSONObject();
		FileEntity file = new FileEntity();
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
			Map<String, MultipartFile> map = multipartRequest.getFileMap();
			for (Entry<String, MultipartFile> entry : map.entrySet()) {
				file = UploadController.uploadFile(entry.getValue());

			}
			baseDao.save(file);
			j = ResponseUtil.getMap(ResponseUtil.TRUE_CODE, "上传成功", file.getId());		    

		} catch (Exception e) {
			e.printStackTrace();
			j = ResponseUtil.getMap(ResponseUtil.OTHER_CODE, "异常", "");
			return j;
		}

		return j;

	}
}
